package pumpeddevs.game.framework;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public abstract class PDStage extends SurfaceView implements SurfaceHolder.Callback, Runnable {
	
	private SurfaceHolder _surfaceHolder = null;
	protected PDActivity _context;
	protected int _screenWidth;
	protected int _screenHeight;
	private Thread _thread;
	private boolean _run = true;
	protected boolean _isPause = false; 
	protected boolean _isFinish;
	
	public PDStage(PDActivity context,int width, int height) {
		super(context);
		this._context = context;
		this._surfaceHolder = getHolder();
		this._surfaceHolder.addCallback(this);
		this._screenWidth = width;
		this._screenHeight = height;
	}
	
	public boolean isFinish() {
		return this._isFinish;
	}
	
	public void setFinish(boolean isFinish) {
		this._isFinish = isFinish;
	}
	
	public abstract void init();
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		this._thread = new Thread(this);
		this._thread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		
	}
	
	protected abstract void render(Canvas canvas);
	protected abstract void updatePhysics();
	
	public void stop() {
		this._run = false;
	}

	@Override
	public void run() {
		this.init();
		while (this._run) {
			if(!this._isPause) {
				Canvas canvas = null;
				try {
					canvas = this._surfaceHolder.lockCanvas();	
					synchronized (this._surfaceHolder) {
						updatePhysics();
						render(canvas);
					}
					
				} finally {
					if(canvas !=null) {
						this._surfaceHolder.unlockCanvasAndPost(canvas);
					}
				}
			}
		}
	}
}
